const orderService = require('../service/order.service')
const userService = require('../service/user.service')
const { v4 } = require('uuid')
const R = require('../utils/R')
const {
    CREATE_ORDER_EXCEPTION,
    GET_ORDER_LIST_EXCEPTION,
    FINISH_ORDER_EXCEPTION,
    REMOVE_ORDER_EXCEPTION
} = require('../error/errorType')

class OrderController {
    // 创建/结束订单
    async toggle(ctx, next) {
        try {
            const mode = ctx.mode
            const { id: userId } = ctx.userInfo
            const { id: stadiumId } = ctx.stadiumInfo
            if (mode == 'start') {
                let status = 0, orderNo = v4(), amount = 0
                let result = await orderService.insertOrder(status, orderNo, userId, stadiumId, amount)
                if (result.insertId) {
                    let item = await orderService.getOne(stadiumId, userId)
                    ctx.dto = R.ok('创建订单成功', item)
                } else {
                    ctx.dto = R.error(CREATE_ORDER_EXCEPTION)
                }
            } else if (mode == 'update') {
                console.log('重设订单')
                const { orderId } = ctx
                let orderNo = v4()
                let result = await orderService.resetOrder(orderNo, orderId)
                if (result.affectedRows == 1) {
                    let [ item ] = await orderService.getOne(stadiumId, userId)
                    delete item.amount
                    ctx.dto = R.ok('创建订单成功', item)
                } else {
                    ctx.dto = R.error(CREATE_ORDER_EXCEPTION)
                }
            } else { // mode == 'end'
                const { orderId, cost, rest } = ctx
                const { id: userId } = ctx.userInfo
                let result = await orderService.updateAmount(cost, orderId)
                if (result.affectedRows == 1) {
                    await userService.updateAmount(rest - cost, userId)
                    ctx.dto = R.ok(`结算订单成功, 本次结算${cost}元`, null)
                } else {
                    ctx.dto = R.error(FINISH_ORDER_EXCEPTION)
                }
            }
        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(CREATE_ORDER_EXCEPTION), ctx)
        }
        await next()
    }

    // 获取订单列表
    async list(ctx, next) {
        try {
            const { id: userId } = ctx.userInfo
            const { pageNum, currentPage, pageSize } = ctx.pager
            let rows = await orderService.list(userId, pageNum, pageSize)
            rows.forEach(item => {
                item.statusText = item.status == 0 ? '进行中' : '已完成'
                item.createAt = new Date(item.createAt).toLocaleString()
                item.updateAt = new Date(item.updateAt).toLocaleString()
            })
            let total = await orderService.getTotal(userId)
            let result = { total, currentPage, pageSize, size: rows.length, rows }
            ctx.dto = R.ok('获取订单列表成功', result)
        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(GET_ORDER_LIST_EXCEPTION), ctx)
        }
        await next()
    }

    // 删除订单
    async remove(ctx, next) {
        try {
            const orderId= ctx.orderId
            let result = await orderService.remove(orderId)
            if (result.affectedRows == 1) {
                ctx.dto = R.ok('删除订单成功', null)
            } else {
                ctx.dto = R.error(REMOVE_ORDER_EXCEPTION)
            }
        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(REMOVE_ORDER_EXCEPTION), ctx)
        }
        await next()
    }
}

module.exports = new OrderController()